import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpClient {
    private DatagramSocket socket = null;
    private String severIp;
    private int severPort;
    public UdpClient(String severIp,int severPort) throws SocketException {
        socket = new DatagramSocket();
        this.severIp = severIp;
        this.severPort = severPort;
    }
    public void start() throws IOException {
        System.out.println("UdpClient 启动！");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("->");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(this.severIp),this.severPort);
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpClient udpClient = new UdpClient("127.0.0.1",9090);
        udpClient.start();
    }
}
